package br.ucb.musicbay.servlet;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.ucb.musicbay.album.Album;
import br.ucb.musicbay.album.AlbumBO;
import br.ucb.musicbay.artista.Artista;
import br.ucb.musicbay.artista.ArtistaBO;
import br.ucb.musicbay.usuario.Usuario;
import br.ucb.musicbay.usuario.UsuarioBO;

public class ImageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String tipo = req.getParameter("tipo");

		if (tipo.equals("a")) {
			Integer idArtista = Integer.parseInt(req.getParameter("id"));
			ArtistaBO artistabo = new ArtistaBO();
			Artista artista = artistabo.recoverById(idArtista);

			if (artista != null) {
				if(artista.getImg() == null){
					artista.setImg(getImgPadrao());
				}
				resp.getOutputStream().write(artista.getImg());
				resp.setContentType("image/jpg");
			}
		} else if (tipo.equals("u")) {
			Integer idAlbum = Integer.parseInt(req.getParameter("id"));
			AlbumBO albumBo = new AlbumBO();
			Album album = albumBo.recoverById(idAlbum);

			if (album != null) {
				if(album.getImg() == null){
					album.setImg(getImgPadrao());
				}
				resp.getOutputStream().write(album.getImg());
				resp.setContentType("image/jpg");
			}
		} else if (tipo.equals("l")) {
			Integer idUsuario = Integer.parseInt(req.getParameter("id"));
			UsuarioBO usuarioBo = new UsuarioBO();
			Usuario usuario = usuarioBo.recoverById(idUsuario);

			if (usuario != null) {
				if(usuario.getImg() == null){
					usuario.setImg(getImgPadrao());
				}
				resp.getOutputStream().write(usuario.getImg());
				resp.setContentType("image/jpg");
			}
		}
	}
	
	private byte[] getImgPadrao() throws IOException{
		String caminho = getServletContext().getRealPath("/");
		caminho=caminho+"resources/imagens/musicbay/notFound.png";
		System.out.println("PATH - "+caminho);
		File file = new File(caminho);
		BufferedImage img = ImageIO.read(file);
		ByteArrayOutputStream bytesImg = new ByteArrayOutputStream();
		ImageIO.write((BufferedImage) img, "jpg", bytesImg);
		bytesImg.flush();
		byte[] byteArray = bytesImg.toByteArray();
		bytesImg.close();
		return byteArray;
	}
}
